package main

import (
	"com.jtthink/go_rabbitMQ/add_init"
	"com.jtthink/go_rabbitMQ/lib"
	"com.jtthink/go_rabbitMQ/user_reg/helper"
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"time"
)

func Send(msg amqp.Delivery) {
	time.Sleep(time.Second * 1)

	userID := string(msg.Body)

	isfail := true

	delay := msg.Headers["x-delay"]

	if isfail {

		r := helper.SetNotify(userID, 5)
		newDelay := int(delay.(int32)) * 2

		if r > 0 {

			err := myClient.SendDelayedMessage(lib.ROUTER_KEY_USER_REG, lib.EXCHANGE_USER_DELAYED, userID, newDelay)
			if err != nil {
				log.Println(err)
			}
			log.Println("userID: ", userID, "重试: ", newDelay)
		} else {

			log.Printf("用户:%s 达到了最大重试次数", userID)

		}
		msg.Reject(false) //丢弃

	} else {
		fmt.Println("收到消息 ID: ", msg.DeliveryTag)
		msg.Ack(false)
	}

}

func SendMail(msgs <-chan amqp.Delivery, c string) {

	for msg := range msgs {

		go Send(msg)
		fmt.Println("向我开炮", c)

		//if c == "c1" {
		//	fmt.Println("模拟出错")
		//	//重新入列
		//	msg.Reject(true)
		//	continue
		//}

	}

}

var myClient *lib.MQ

func main() {

	myClient = lib.NewMq()

	add_init.InitDB()

	//消费者限流
	err := myClient.Ch.Qos(2, 0, false)
	if err != nil {
		fmt.Println(err.Error())
	}

	myClient.Consume(lib.QUEUE_NEW_USER, "c1", "c1", SendMail)

}
